package com.niepan.modules.zhinenganjianback.service.impl;

import com.alibaba.fastjson.JSON;
import com.niepan.common.utils.SplitDateUtils;
import com.niepan.common.utils.minio.MinIOUtil;
import com.niepan.modules.zhinenganjianback.common.EM_INSIDE_OBJECT_TYPE;
import com.niepan.modules.zhinenganjianback.dao.ContrabandListMapper;
import com.niepan.modules.zhinenganjianback.service.ContrabandListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:liuchenyu
 * @data:2023/02/27
 */
@Service
public class ContrabandServiceListImpl implements ContrabandListService {

    @Value("${file.save-path}")
    private String savePath;

    @Autowired
    private MinIOUtil minIOUtil;

    @Autowired
    private ContrabandListMapper contrabandListMapper;


    @Override
    public List<Map<String, Object>> getArea() {
        List<Map<String, Object>> res = contrabandListMapper.getArea();
        return res;
    }

    @Override
    public List<Map<String, Object>> getItem(String uniqueCode,
                                             String machineGrade,
                                             String machineBrand,
                                             String startTime,
                                             String endTime) {
        List<Map<String, Object>> res = contrabandListMapper.getItem(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        return res;
    }

    @Override
    public List<Map<String, Object>> getCount(String uniqueCode,String machineGrade, String machineBrand, String startTime, String endTime) {
        Map<String, Object> map = contrabandListMapper.getCount(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        //将查出来的一整个对象按照不同的违禁品类型type分成多个单独的对象
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map.Entry<String, Object> entry : entries) {
            Map<String,Object> res = new HashMap<>();
            String key = entry.getKey();
            res.put("name",key);
            Long value = (Long) entry.getValue();
            res.put("value",value);
            int valueByNote = EM_INSIDE_OBJECT_TYPE.getValueByNote(key);
            res.put("id",valueByNote);
            list.add(res);
        }
        List<Map<String, Object>> res = list.stream().sorted((e1, e2) -> {
            // 升序
            // return Long.compare((Long) e1.get("value"), (Long) e2.get("value"));
            // 降序
            return -Long.compare((Long) e1.get("value"), (Long) e2.get("value"));
        }).collect(Collectors.toList());
        return res;
    }

    @Override
    public List<Map<String, Object>> getDetail(String uuid) {
        List<Map<String, Object>> list = contrabandListMapper.getDetail(uuid);
        return list;
    }

    @Override
    public List<Map<String, Object>> getCentre(String uniqueCode) {
//        String substring = uniqueCode.substring(0, uniqueCode.lastIndexOf("-"));
        List<Map<String, Object>> list = contrabandListMapper.getCentre(uniqueCode);
        List<String> channel = this.getChannel(uniqueCode);
        for (Map<String, Object> stringObjectMap : list) {
            stringObjectMap.put("channel",channel);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getTotal(String uniqueCode,String machineGrade, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> list = contrabandListMapper.getTotal(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        return list;
    }

    @Override
    public List<Map<String, Object>> getCountDetail(String uniqueCode,
                                                    String machineGrade,
                                                    String machineBrand,
                                                    String startTime,
                                                    String endTime,
                                                    String typeId) {
        List<Map<String, Object>> list = contrabandListMapper.getCountDetail(uniqueCode,machineGrade,machineBrand,startTime,endTime,typeId);
        try {
            for (Map<String, Object> stringObjectMap : list) {
                String device_sn = (String) stringObjectMap.get("device_sn");
                String line_code = (String) stringObjectMap.get("line_code");
                String current_time = (String) stringObjectMap.get("current_time");
                String substring = current_time.substring(0,10);
                String time = substring.replaceAll("-", "");
                String name = (String) stringObjectMap.get("name");
                File file = new File(savePath + device_sn + line_code + "/" + time + "/" + name);
                FileInputStream inputFile = new FileInputStream(file);
                byte[] buffer = new byte[(int)file.length()];
                inputFile.read(buffer);
                inputFile.close();
                stringObjectMap.put("picture",new BASE64Encoder().encode(buffer));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }


    public List<List<Map<String, Object>>> getCountStatisticsOld
            (String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {

        //使用工具类，传入两个时间范围，返回这两个时间范围内的所有日期，并保存在一个集合中
        List<String> everyDay = SplitDateUtils.findEveryDay(startTime, endTime);

        List<List<Map<String, Object>>> result = new ArrayList<>();
        for (String day : everyDay) {
            Set<Map.Entry<String, Object>> entries = null;
            //将查出来的一整个对象按照不同的违禁品类型type分成多个单独的对象
            List<Map<String, Object>> everyList = contrabandListMapper.getCountStatistics(uniqueCode,machineGrade,machineBrand,day);
            for (Map<String, Object> map : everyList) {
                entries = map.entrySet();
            }
            List<Map<String, Object>> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : entries) {
                Map<String,Object> res = new HashMap<>();
                String key = entry.getKey();
                res.put("name",key);
                Long value = (Long) entry.getValue();
                res.put("value",value);
                int valueByNote = EM_INSIDE_OBJECT_TYPE.getValueByNote(key);
                res.put("id",valueByNote);
                res.put("day",day);
                list.add(res);
            }
            //对查询出来的物品进行排序
            List<Map<String, Object>> res = list.stream().sorted((e1, e2) -> {
                return -Long.compare((Long) e1.get("value"), (Long) e2.get("value"));
            }).limit(5).collect(Collectors.toList());
            result.add(res);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getCountStatistics
            (String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {
        //使用工具类，传入两个时间范围，返回这两个时间范围内的所有日期，并保存在一个集合中
        List<String> everyDay = SplitDateUtils.findEveryDay(startTime, endTime);

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parseStart = LocalDateTime.parse(startTime, df);
        LocalDateTime parseEnd = LocalDateTime.parse(endTime, df);
        int hour = 1;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date StartDate = format.parse(startTime);
            Date EndDate = format.parse(endTime);
            int i = differentDaysByMillisecond(StartDate, EndDate);
            if (i <= 1){
                hour = 1;
            }else {
                hour = 24;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<LocalDateTime> localDateTimes = this.splitTime(parseStart, parseEnd, hour);
        List<Map<String, Object>> result = new ArrayList<>();
        EM_INSIDE_OBJECT_TYPE[] values = EM_INSIDE_OBJECT_TYPE.values();

        List<List<Map<String, Object>>> countByType = new ArrayList<>();

        for (int i = 1; i < localDateTimes.size(); i++) {
            String localTimeStart = df.format(localDateTimes.get(i - 1));
            String localTimeEnd = df.format(localDateTimes.get(i));
            countByType.add(contrabandListMapper.getCountByType(uniqueCode,machineGrade,machineBrand,localTimeStart,localTimeEnd));
        }

        for (EM_INSIDE_OBJECT_TYPE value : values) {
            Map<String,Object> map = new HashMap<>();
            List<Long> count = new ArrayList<>();
            map.put("type",value.getValue());
            map.put("name",value.getNote());
            List<String> time = new ArrayList<>();
            for (int i = 1; i < localDateTimes.size(); i++) {
                String format1 = df.format(localDateTimes.get(i - 1));
                time.add(format1);
            }
            map.put("day",time);
//
//            for (int i = 1; i < localDateTimes.size(); i++) {
//                String localTimeStart = df.format(localDateTimes.get(i - 1));
//                String localTimeEnd = df.format(localDateTimes.get(i));
//                count.add(contrabandListMapper.getCountByType(uniqueCode,machineGrade,machineBrand,localTimeStart,localTimeEnd,value.getValue()));
//                map.put("count",count);
//            }

            for (int i = 0; i < localDateTimes.size() - 1; i++) {
                List<Map<String, Object>> maps = countByType.get(i);
                for (Map<String, Object> stringObjectMap : maps) {
                    if (stringObjectMap.get("em_obj_type") != null && value.getValue() == (Integer) stringObjectMap.get("em_obj_type")){
                        count.add((Long)stringObjectMap.get("count1"));
                    }
                }
                count.add(0l);
            }
            map.put("count",count);

            result.add(map);
        }
//        List<Map<String, Object>> result = new ArrayList<>();
//        EM_INSIDE_OBJECT_TYPE[] values = EM_INSIDE_OBJECT_TYPE.values();
//        for (EM_INSIDE_OBJECT_TYPE value : values) {
//            Map<String,Object> map = new HashMap<>();
//            List<String> count = new ArrayList<>();
//            map.put("type",value.getValue());
//            map.put("name",value.getNote());
//            map.put("day",everyDay);
//            for (String day : everyDay) {
//                count.add(contrabandListMapper.getCountByType(uniqueCode,machineGrade,machineBrand,day,value.getValue()));
//                map.put("count",count);
//            }
//            result.add(map);
//        }
        return result;
    }

    @Override
    public List getPicture(String uniqueCode,String startTime,String endTime,String lineCode) {
        List<Map<String, Object>> list = contrabandListMapper.getPicture(uniqueCode,startTime,endTime,lineCode);
        List res = new ArrayList();
        for (Map<String, Object> stringObjectMap : list) {
            try {
                String device_sn = (String) stringObjectMap.get("device_sn");
//            String time11 = (String) stringObjectMap.get("time");
//            String trim = time11.substring(12).trim();
                String line_code = (String) stringObjectMap.get("line_code");
                Integer count = (Integer) stringObjectMap.get("count");
                String current_time = (String) stringObjectMap.get("current_time");
                String complet_time = (String) stringObjectMap.get("complet_time");
                String ajj_time = (String) stringObjectMap.get("ajj_time");
//            String currentTime = current_time.substring(0,19);
                stringObjectMap.put("current_time",current_time);
                stringObjectMap.put("ajj_time",ajj_time);
                //大华对某些图片不处理
                if (current_time == null || complet_time == null || count ==null){
                    String substring = current_time.substring(0,10);
                    String time = substring.replaceAll("-", "");
                    String name = (String) stringObjectMap.get("name");
//                    stringObjectMap.put("name",AesEncryptUtil.encrypt(name, AesEncryptUtil.KEY, AesEncryptUtil.IV));
                    File file = new File(savePath + device_sn + line_code + "/" + time + "/" + name);
                    FileInputStream inputFile = new FileInputStream(file);
                    byte[] buffer = new byte[(int)file.length()];
                    inputFile.read(buffer);
                    inputFile.close();
                    stringObjectMap.put("picture",new BASE64Encoder().encode(buffer));
                    stringObjectMap.put("count",0);
                    stringObjectMap.put("complet_time",current_time);
                    continue;
                }
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
                //将String转换为localDateTime类型
                LocalDateTime localDateTime1 = LocalDateTime.parse(current_time,dateTimeFormatter);
                LocalDateTime localDateTime2 = LocalDateTime.parse(complet_time,dateTimeFormatter);
                //LocalDateTime自带时间差计算（开始时间，结束时间）
                Duration duration = Duration.between(localDateTime1,localDateTime2);
                long scanTime = duration.toMillis();
                stringObjectMap.put("scanTime",scanTime);

//            String completTime = complet_time.substring(0,19);
                stringObjectMap.put("complet_time",complet_time);


                String picture_id = (String) stringObjectMap.get("picture_id");
                List<String> objType = contrabandListMapper.getObjType(picture_id);
                List<String> objName = new ArrayList<>();
                for (String type : objType) {
                    String noteByValue = EM_INSIDE_OBJECT_TYPE.getNoteByValue(Integer.valueOf(type));
                    objName.add(noteByValue);
                }
                //去重
                List<String> collect = objName.stream().distinct().collect(Collectors.toList());
                stringObjectMap.put("objName",collect);
                //假的网点数据
//            List<String> network = new ArrayList<>();
//            network.add("萧山南部营业部");
//            network.add("萧山蜀山分部");
//            network.add("闻堰分公司");
                stringObjectMap.put("network","外围仓");
//            System.out.println(network.get(list.size() % 3));

                String substring = current_time.substring(0,10);
                String time = substring.replaceAll("-", "");
                String name = (String) stringObjectMap.get("name");
//                stringObjectMap.put("name",AesEncryptUtil.encrypt(name, AesEncryptUtil.KEY, AesEncryptUtil.IV));
                File file = new File(savePath + device_sn + line_code + "/" + time + "/" + name);

                FileInputStream inputFile = new FileInputStream(file);
                byte[] buffer = new byte[(int)file.length()];
                inputFile.read(buffer);
                inputFile.close();
                stringObjectMap.put("picture",new BASE64Encoder().encode(buffer));
                stringObjectMap.put("picPath",device_sn + line_code + "/" + time + "/" + name);
//                stringObjectMap.put("picPath","require('../../../../" + device_sn + line_code + "/" + time + "/" + name + "')");
                String resultStr= JSON.toJSONString(stringObjectMap);
                res.add(resultStr);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getCountByHour(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parseStart = LocalDateTime.parse(startTime, df);
        LocalDateTime parseEnd = LocalDateTime.parse(endTime, df);
        int hour = 1;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date StartDate = format.parse(startTime);
            Date EndDate = format.parse(endTime);
            int i = differentDaysByMillisecond(StartDate, EndDate);
            if (i <= 1){
                hour = 1;
            }else {
                hour = 24;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<LocalDateTime> localDateTimes = this.splitTime(parseStart, parseEnd, hour);
        List<Map<String,Object>> result = new ArrayList<>(localDateTimes.size());

        for (int i = 1; i < localDateTimes.size() - 1; i++) {
            Map<String,Object> mapRes = new HashMap<>();
            String localTimeStart = df.format(localDateTimes.get(i));
            String localTimeEnd = df.format(localDateTimes.get(i+1));
            Map<String, Object> map = contrabandListMapper.getCount(uniqueCode,machineGrade,machineBrand,localTimeStart,localTimeEnd);
            //将查出来的一整个对象按照不同的违禁品类型type分成多个单独的对象
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            List<Map<String, Object>> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : entries) {
                Map<String,Object> res = new HashMap<>();
                String key = entry.getKey();
                if ("鞋子".equals(key) || "杠子".equals(key)  || "金属".equals(key)  || "爆炸物".equals(key)  || "象牙".equals(key)  || "书籍".equals(key)
                        || "光盘".equals(key) || "锤子".equals(key) || "钳子".equals(key) || "螺丝刀".equals(key) || "扳手".equals(key) ||
                        "电击棍".equals(key) || "手枪".equals(key) || "折叠刀".equals(key) || "尖刀".equals(key) || "菜刀".equals(key) ||
                        "美工刀".equals(key) || "烟花".equals(key) || "爆竹".equals(key) || "粉末".equals(key) || "难穿透物品".equals(key)){
                    continue;
                }
                res.put("name",key);
                Long value = (Long) entry.getValue();
                res.put("value",value);
                int valueByNote = EM_INSIDE_OBJECT_TYPE.getValueByNote(key);
                res.put("id",valueByNote);
                list.add(res);
            }
//            List<Map<String, Object>> res = list.stream().sorted((e1, e2) -> {
//                // 升序
//                // return Long.compare((Long) e1.get("value"), (Long) e2.get("value"));
//                // 降序
//                return -Long.compare((Long) e1.get("value"), (Long) e2.get("value"));
//            }).collect(Collectors.toList());
            mapRes.put("time",df.format(localDateTimes.get(i)));
            mapRes.put("data",list);
            result.add(mapRes);
        }
        return result;
    }

    @Override
    public List<String>  getChannel(String uniqueCode) {
        return contrabandListMapper.getChannel(uniqueCode);
    }

    @Value("${file.picPath}")
    private String picPath;

    @Override
    public List getSpPicture(String uniqueCode, String startTime, String endTime, String lineCode,Boolean isDanger) {
        List<Map<String, Object>> list = contrabandListMapper.getSpPicture(uniqueCode,startTime,endTime,lineCode,isDanger);
        for (Map<String, Object> stringObjectMap : list) {
            try {
                Long timestamp = (Long) stringObjectMap.get("timestamp");
                Date date = new Date(timestamp);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                String formatTime = sdf.format(date);
                String device_ip = (String) stringObjectMap.get("device_ip");
                String create_time = (String) stringObjectMap.get("create_time");

                try {
                    Date ajjDate = sdf.parse(create_time); // 将时间字符串解析为 Date 对象
                    long timeMillis = ajjDate.getTime(); // 转化为时间戳
                    timeMillis -= 300; // 减去 300ms

                    Date newDate = new Date(timeMillis); // 转化为新的 Date 对象
                    String newTimeStr = sdf.format(newDate); // 将新的日期格式化为字符串
                    stringObjectMap.put("timestamp",newTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                String substring = create_time.substring(0,10);
//                stringObjectMap.put("create_time",substring);
                String picture_id = (String) stringObjectMap.get("id");
                stringObjectMap.put("count",(Integer) stringObjectMap.get("n_object_num"));
                List<String> objType = contrabandListMapper.getObjType(picture_id);
                List<String> objName = new ArrayList<>();
                for (String type : objType) {
                    String noteByValue = EM_INSIDE_OBJECT_TYPE.getNoteByValue(Integer.valueOf(type));
                    objName.add(noteByValue);
                }
                //去重
                List<String> collect = objName.stream().distinct().collect(Collectors.toList());
                stringObjectMap.put("objName",collect);
                //假的网点数据
                stringObjectMap.put("network","外围仓");
//                stringObjectMap.put("name",AesEncryptUtil.encrypt(name, AesEncryptUtil.KEY, AesEncryptUtil.IV));
//                File file = new File(picPath + device_ip + "/" + substring + "/" + timestamp + "related_0.jpg");
//                FileInputStream inputFile = new FileInputStream(file);
//                byte[] buffer = new byte[(int)file.length()];
//                inputFile.read(buffer);
//                inputFile.close();
//                stringObjectMap.put("picture",new BASE64Encoder().encode(buffer));
//                stringObjectMap.put("picPath",device_ip + "/" + substring + "/" + timestamp + "related_0.jpg");
                stringObjectMap.put("picPath",minIOUtil.getPreviewFileUrl(timestamp + "related_0.jpg"));
                stringObjectMap.put("picPathZhiNeng",minIOUtil.getPreviewFileUrl(timestamp + "related_1.jpg"));
//                stringObjectMap.put("picPath","require('../../../../" + device_sn + line_code + "/" + time + "/" + name + "')");
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getSpItem(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> res = contrabandListMapper.getSpItem(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        return res;
    }

    @Override
    public List<Map<String, Object>> getSpCountByDay(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parseStart = LocalDateTime.parse(startTime, df);
        LocalDateTime parseEnd = LocalDateTime.parse(endTime, df);
        int hour = 1;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date StartDate = format.parse(startTime);
            Date EndDate = format.parse(endTime);
            int i = differentDaysByMillisecond(StartDate, EndDate);
            if (i <= 1){
                hour = 2;
            }else {
                hour = 24;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Map<String, Object>> list = new ArrayList<>();
        List<LocalDateTime> localDateTimes = this.splitTime(parseStart, parseEnd, hour);

        for (int i = 1; i < localDateTimes.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            String localTimeStart = df.format(localDateTimes.get(i - 1));
            String localTimeEnd = df.format(localDateTimes.get(i));
            map.put("name",df.format(localDateTimes.get(i)));
            map.putAll(contrabandListMapper.getSpCountByDay(uniqueCode,machineGrade,machineBrand,localTimeStart,localTimeEnd));
            list.add(map);
        }
        /*//使用工具类，传入两个时间范围，返回这两个时间范围内的所有日期，并保存在一个集合中
        List<String> everyDay = SplitDateUtils.findEveryDay(startTime, endTime);

        List<Map<String, Object>> list = new ArrayList<>();
        for (String day : everyDay) {
            Map<String, Object> map = new HashMap<>();
            map.put("name",day);
            map.putAll(contrabandListMapper.getCountByDay(uniqueCode,machineGrade,machineBrand,day));
            list.add(map);
        }*/
        return list;
    }

    @Override
    public List<Map<String, Object>> getSpTotal(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> list = contrabandListMapper.getSpTotal(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        return list;
    }

    @Override
    public List<Map<String, Object>> getSpDangerTotal(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> list = contrabandListMapper.getSpDangerTotal(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        return list;
    }

    @Override
    public List<Map<String, Object>> getSpCountDetail(String machineGrade, String machineBrand, String startTime, String endTime, String typeId, String uniqueCode) {
        List<Map<String, Object>> list = contrabandListMapper.getSpCountDetail(uniqueCode,machineGrade,machineBrand,startTime,endTime,typeId);
        try {
            for (Map<String, Object> stringObjectMap : list) {
                String device_ip = (String) stringObjectMap.get("device_ip");
                String create_time = (String) stringObjectMap.get("create_time");
                String substring = create_time.substring(0,10);
//                String time = substring.replaceAll("-", "");
                Long name = (Long) stringObjectMap.get("timestamp");
//                File file = new File(picPath + device_ip + "/" + substring + "/" + name + "related_0.jpg");
//                FileInputStream inputFile = new FileInputStream(file);
//                byte[] buffer = new byte[(int)file.length()];
//                inputFile.read(buffer);
//                inputFile.close();
//                stringObjectMap.put("picture",new BASE64Encoder().encode(buffer));

                stringObjectMap.put("picPath",device_ip + "/" + substring + "/" + name + "related_0.jpg");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getLineCode() {
        return contrabandListMapper.getLineCode();
    }

    @Override
    public String getReportData(String imageId) {
        String res = contrabandListMapper.getReportData(imageId);
        return res.replaceAll("\\\\","");
    }

    @Override
    public List getSpPictureTwice(String uniqueCode, String startTime, String endTime, String lineCode, Boolean isDanger) {
        List<Map<String, Object>> list = contrabandListMapper.getSpPictureTwice(uniqueCode,startTime,endTime,lineCode,isDanger);
        for (Map<String, Object> stringObjectMap : list) {
            try {
                Long timestamp = (Long) stringObjectMap.get("timestamp");
                Date date = new Date(timestamp);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                String formatTime = sdf.format(date);
                String device_ip = (String) stringObjectMap.get("device_ip");
                String create_time = (String) stringObjectMap.get("create_time");

                try {
                    Date ajjDate = sdf.parse(create_time); // 将时间字符串解析为 Date 对象
                    long timeMillis = ajjDate.getTime(); // 转化为时间戳
                    timeMillis -= 300; // 减去 300ms

                    Date newDate = new Date(timeMillis); // 转化为新的 Date 对象
                    String newTimeStr = sdf.format(newDate); // 将新的日期格式化为字符串
                    stringObjectMap.put("timestamp",newTimeStr);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                String substring = create_time.substring(0,10);
//                stringObjectMap.put("create_time",substring);
                String picture_id = (String) stringObjectMap.get("id");
                stringObjectMap.put("count",(Integer) stringObjectMap.get("n_object_num"));
                List<String> objType = contrabandListMapper.getObjType(picture_id);
                List<String> objName = new ArrayList<>();
                for (String type : objType) {
                    String noteByValue = EM_INSIDE_OBJECT_TYPE.getNoteByValue(Integer.valueOf(type));
                    objName.add(noteByValue);
                }
                //去重
                List<String> collect = objName.stream().distinct().collect(Collectors.toList());
                stringObjectMap.put("objName",collect);
                //假的网点数据
                stringObjectMap.put("network","外围仓");
//                stringObjectMap.put("name",AesEncryptUtil.encrypt(name, AesEncryptUtil.KEY, AesEncryptUtil.IV));
//                File file = new File(picPath + device_ip + "/" + substring + "/" + timestamp + "related_0.jpg");
//                FileInputStream inputFile = new FileInputStream(file);
//                byte[] buffer = new byte[(int)file.length()];
//                inputFile.read(buffer);
//                inputFile.close();
//                stringObjectMap.put("picture",new BASE64Encoder().encode(buffer));
//                stringObjectMap.put("picPath",device_ip + "/" + substring + "/" + timestamp + "related_0.jpg");
//                stringObjectMap.put("picPathZhiNeng",device_ip + "/" + substring + "/" + timestamp + "related_1.jpg");
                stringObjectMap.put("picPath",minIOUtil.getPreviewFileUrl(timestamp + "related_0.jpg"));
                stringObjectMap.put("picPathZhiNeng",minIOUtil.getPreviewFileUrl(timestamp + "related_1.jpg"));
//                stringObjectMap.put("picPath","require('../../../../" + device_sn + line_code + "/" + time + "/" + name + "')");
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getSpTotalTwice(String uniqueCode, String lineCode, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> list = contrabandListMapper.getSpTotalTwice(uniqueCode,lineCode,machineBrand,startTime,endTime);
        return list;
    }

    @Override
    public List<Map<String, Object>> getSpDangerTotalTwice(String uniqueCode, String lineCode, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> list = contrabandListMapper.getSpDangerTotalTwice(uniqueCode,lineCode,machineBrand,startTime,endTime);
        return list;
    }

    @Override
    public List<Map<String, Object>> getDangerTotal(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {
        List<Map<String, Object>> list = contrabandListMapper.getDangerTotal(uniqueCode,machineGrade,machineBrand,startTime,endTime);
        return list;
    }

    @Override
    public List<Map<String, Object>> getCountByDay(String uniqueCode, String machineGrade, String machineBrand, String startTime, String endTime) {

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parseStart = LocalDateTime.parse(startTime, df);
        LocalDateTime parseEnd = LocalDateTime.parse(endTime, df);
        int hour = 1;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date StartDate = format.parse(startTime);
            Date EndDate = format.parse(endTime);
            int i = differentDaysByMillisecond(StartDate, EndDate);
            if (i <= 1){
                hour = 2;
            }else {
                hour = 24;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Map<String, Object>> list = new ArrayList<>();
        List<LocalDateTime> localDateTimes = this.splitTime(parseStart, parseEnd, hour);

        for (int i = 1; i < localDateTimes.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            String localTimeStart = df.format(localDateTimes.get(i - 1));
            String localTimeEnd = df.format(localDateTimes.get(i));
            map.put("name",df.format(localDateTimes.get(i)));
            map.putAll(contrabandListMapper.getCountByDay(uniqueCode,machineGrade,machineBrand,localTimeStart,localTimeEnd));
            list.add(map);
        }
        /*//使用工具类，传入两个时间范围，返回这两个时间范围内的所有日期，并保存在一个集合中
        List<String> everyDay = SplitDateUtils.findEveryDay(startTime, endTime);

        List<Map<String, Object>> list = new ArrayList<>();
        for (String day : everyDay) {
            Map<String, Object> map = new HashMap<>();
            map.put("name",day);
            map.putAll(contrabandListMapper.getCountByDay(uniqueCode,machineGrade,machineBrand,day));
            list.add(map);
        }*/
        return list;
    }

    /**
     * 按照指定的小时分割给定的时间
     * @param start
     * @param end
     * @param hours
     * @return
     */
    public List<LocalDateTime> splitTime(LocalDateTime start, LocalDateTime end, int hours) {
        List<LocalDateTime> result = new ArrayList<>();
        long hoursBetween = ChronoUnit.HOURS.between(start, end);
        for (int i = 0; i <= hoursBetween; i += hours) {
            result.add(start.plusHours(i));
        }
        return result;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1,Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }


}